// navigation.navigate('Send')

import React, {useContext, useEffect, useState} from 'react';
import { Platform, Alert, View, TouchableOpacity, ImageBackground, Dimensions, FlatList} from 'react-native';
import {Button, Image, Text, Divider, ListItem, Icon} from 'react-native-elements';

import LocaleContext from '../libs/locale';
import WalletContext from '../libs/wallet';
import {getTokenTxs, getTxs} from '../libs/nodes';
import {formartMoney, timeFormat} from '../libs/helpers';
import accountIcon from '../assets/Assets/send.account.png';
import scan from '../assets/Assets/scan.png';

import tranout from '../assets/tranout.png';
import tranin from '../assets/tranin.png';
import logo from '../assets/logo.png';

import AsyncStorage from '@react-native-async-storage/async-storage';
import {constansts} from "../libs/constansts";

const {width, height} = Dimensions.get("window");
console.log("屏幕=" + width + " " + height);

const PreSend = ({navigation, route}: any) => {
    const locale: any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [recentTxs, setRecentTxs] = useState<any>([]);
    const coin = route?.params?.coin || "SAT";
    const tokenAddress = route?.params?.tokenAddress || "";
    const tokenHttpInfo =  route?.params?.item;

    const [loadMore, setLoadMore] = useState(true);
    const [lastIndex, setLastIndex] = useState(0);
    const [lastFetched, setLastFetched] = useState(0);

    useEffect(() => {
        const work = async () => {
            try {
                if (!loadMore) {
                    return;
                }
                setLoadMore(false);

                let li = lastIndex;
                let lf = lastFetched;
                if (lastFetched === 20) {
                    li += 1;
                    lf = 0;
                    setLastIndex(li);
                    setLastFetched(lf);
                }

                var txs;
                console.log("coin=" + coin);

                if (tokenAddress == "")
                    txs = await getTokenTxs(wallet.address, li * 20, "");
                else {
                    txs = await getTokenTxs(wallet.address, li * 20, tokenAddress);
                }

                setLastFetched(txs.length);
                txs.splice(0, lf);
                setRecentTxs(recentTxs.concat(txs));
            } catch (e) {
                console.log('getTxs:', e);
            }
        };
        console.log("Presend页面的tokenAddress=" + tokenAddress);
        work();
    }, [wallet, loadMore]);

    useEffect(()=>{
        navigation.setOptions({
            headerRight: () => (
                tokenAddress===""?null:
                <TouchableOpacity style={{
                width: 30,
                height: 35,
                marginRight: 20,
                alignItems: "center",
                justifyContent: "center"
            }}
                onPress={()=>{navigation.navigate("TokenInfo",{ConAddress:tokenAddress,coin,tokenHttpInfo})}}
            >
                <Icon type='feather' name='file-text' color='#292929' size={25} />
            </TouchableOpacity>


            ),
        });
    })

    const retrievedMoney = (remarks:any)=>{
        try{
            const res = remarks.split("：");
            return res[1];
        }catch (e) {
            return "0";
        }

    }

    const renderItem = ({item, index}: any) => (
        <View>
            <ListItem
                onPress={() => {
                    console.log(JSON.stringify(item));
                    tokenAddress !== "" ?
                        navigation.push('TxDetails', {tx: item, coin})
                        :
                        (item.type=="contract" && (item.addressOut=="" || item.data.indexOf("transfer")==-1))?
                            navigation.push('Send', {
                                coin: coin,
                                tokenAddress,
                                receiver: ""
                            })
                            :
                            navigation.push('Send', {
                                coin: coin,
                                tokenAddress,
                                receiver: (item.addressOut !== wallet.address ? item.addressOut : item.addressIn)
                            })
                }}>
                {
                    item.addressIn === wallet.address
                        ?
                        <ImageBackground source={tranout} style={{marginTop: -7, width: 20, height: 20}}/>
                        :
                        <ImageBackground source={tranin} style={{marginTop: -7, width: 20, height: 20}}/>
                }
                <View style={{marginLeft: -5}}>
                    <Text style={{color: 'black', fontSize: 17, paddingBottom: 5}}>
                        {
                        coin == "SAT" ?
                            (item.type=="contract" && (item.data.indexOf("create")>-1)?
                                locale?._('Assets.tx.contractRelease')
                                    :
                             item.type=="contract" && (item.data.indexOf("transfer")==-1)?
                                 locale?._('Assets.tx.contractCall')
                                     :
                            (item.addressIn !== wallet.address && (item.addressIn === null ||  item.addressOut ===null)?
                                    "000000...000000"
                                    :
                                    item.addressIn === wallet.address?
                                    item.addressOut.slice(0, 6) + "..." + item.addressOut.slice(-6)
                                    :
                                    item.addressIn.slice(0, 6) + "..." + item.addressIn.slice(-6)
                            ))
                            :
                            (item.type=="contract" && (item.data.indexOf("create")>-1))?
                                locale?._('Assets.tx.contractRelease')
                                :
                                (item.data.substring(10, 43) === wallet.address ?
                                    item.type=="contract" && (item.data.indexOf("transfer")==-1)?
                                        locale?._('Assets.tx.contractCall')
                                        :
                                        item.addressIn.slice(0, 6) + "..." + item.addressIn.slice(-6)
                                    :
                                    (item.data.indexOf("transfer")==-1)?locale?._('Assets.tx.contractCall'):item.data.substring(10, 43).slice(0,6)+"..."+item.data.substring(10, 43).slice(-6)
                            )
                    }</Text>
                    <Text style={{
                        fontSize: 10,
                        color: 'lightgrey',
                        marginTop: 0,
                        paddingLeft: 5,
                        paddingBottom: 3
                    }}>{timeFormat(item.timestamp)}</Text>
                </View>
                <View style={{flex: 1}}/>
                <View style={{alignItems: 'flex-end', marginRight: 6}}>
                    {
                        coin == "SAT" ? (
                                item.addressIn !== wallet.address
                                ?
                                <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>+{formartMoney(item.amount, 4)}</Text>
                                :
                                (item.data.indexOf("addLiquidity")!==-1?
                                        <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>-{formartMoney(item.data.match(/\"(.*?)\"/)[1],4)}</Text>
                                        :
                                        (
                                            item.data.indexOf("retrieved")!==-1?
                                                <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>+{formartMoney(retrievedMoney(item.remarks),4)}</Text>
                                                :
                                                <Text style={{color:"black",fontSize:16,marginTop:0,fontWeight:"bold",paddingBottom:5}}>-{formartMoney(item.amount, 4)}</Text>

                                        )
                                )
                            ) :
                            (
                                item.data.indexOf("transfer") > -1 ?
                                    (item.addressIn === wallet.address
                                            ?
                                            <Text style={{
                                                color: "black",
                                                fontSize: 16,
                                                marginTop: 0,
                                                fontWeight: "bold",
                                                paddingBottom: 5
                                            }}>-{formartMoney(item.temp, 4)}</Text>
                                            :
                                            <Text style={{
                                                color: "black",
                                                fontSize: 16,
                                                marginTop: 0,
                                                fontWeight: "bold",
                                                paddingBottom: 5
                                            }}>+{formartMoney(item.temp, 4)}</Text>
                                    )
                                    : (
                                        <Text style={{
                                            color: "black",
                                            fontSize: 18,
                                            marginTop: 0,
                                            fontWeight: "bold",
                                            paddingBottom: 5
                                        }}>0</Text>
                                    )
                            )
                    }
                    {
                        <Text style={{
                            color: (item.addressIn === wallet.address ? '#0BBED5' : "#7367E3"),
                            fontSize: 10,
                            paddingBottom: 3
                        }}>{locale._('Assets.txs.success')}</Text>
                    }

                </View>
            </ListItem>
            <View style={{
                height: 0,
                borderTopWidth: 0.5,
                borderColor: "#DCD4D4",
                opacity: 0.7,
                margin: 1,
                marginLeft: 60,
                marginRight: 16,
                marginTop: -5
            }}/>
        </View>
    );

    return (
        <View style={{}}>
            <View style={{
                flexDirection: 'row',
                justifyContent: 'space-around',
                paddingTop: 80,
                paddingBottom: 26,
                backgroundColor: '#FAFBFDFF',
                marginTop:Platform.OS == 'ios' ? 30 : 0
            }}>
                <TouchableOpacity onPress={() => navigation.push('Send', {coin: coin, tokenAddress})}
                                  style={{alignItems: 'center'}}>
                    <ImageBackground source={accountIcon} style={{width: 30, height: 30}}/>
                    <Text style={{
                        fontSize: 15,
                        fontWeight: 'bold',
                        marginTop: 10
                    }}>{locale?._('Assets.send.sendToAccount')}</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => navigation.navigate(('Scan'), {coin: coin, tokenAddress})}
                                  style={{alignItems: 'center'}}>
                    <ImageBackground source={scan} style={{width: 30, height: 30}}/>
                    <Text
                        style={{fontSize: 15, fontWeight: 'bold', marginTop: 10}}>{locale?._('Assets.send.scan')}</Text>
                </TouchableOpacity>
            </View>

            <View style={{}}>
                <Text style={{
                    fontSize: 18,
                    fontWeight: 'bold',
                    padding: 20,
                }}>{locale?._('Assets.send.recent')}</Text>
                <Divider/>
                {
                    <FlatList
                        renderItem={renderItem}
                        data={recentTxs}
                        keyExtractor={item => item.hash}
                        onEndReached={() => setLoadMore(true)}
                        refreshing={false}
                        onRefresh={() => {
                            setLastIndex(0);
                            setLastFetched(0);
                            setRecentTxs([]);
                            setLoadMore(true);
                        }}
                        style={{marginBottom: 520}}
                        ListEmptyComponent={
                            <Text style={{
                                marginTop: 160,
                                fontSize: 20,
                                textAlign: 'center',
                                color: 'grey',
                            }}>{locale._('noContent')}</Text>
                        }/>
                }
            </View>
        </View>
    );
};

export default PreSend;
